<template>
    <!-- 头部 搜索、新增 区域 -->
    <el-row :gutter="20" class="header">
        <el-col :span="6">
            <el-input v-model="search" placeholder="请输入员工名称" clearable>
                <template #append>
                    <el-button @click="getEmployee"> 搜索 </el-button>
                </template>
            </el-input>
        </el-col>
        <el-col :span="6">
            <el-button type="primary" @click="getOrg(); getEmployeeRole(); createDialog = true;">新增</el-button>
        </el-col>
    </el-row>

    <!-- 华丽的分割线 -->
    <el-divider />

    <!-- 表格形式展示house数据 -->
    <div>
        <el-table :data="employeeData" style="width: 100%" max-height="490px">
            <el-table-column prop="id" v-if="false" />
            <el-table-column prop="name" label="员工姓名" width="110" />
            <el-table-column prop="phone" label="账号 / 手机号" width="120" />
            <el-table-column prop="orgId" label="组织id" width="90" v-if="false" />
            <el-table-column prop="orgName" label="所属组织" width="100" v-if="false" />
            <el-table-column prop="orgPath" label="所属组织路径" width="150" />
            <el-table-column prop="roleId" label="角色id" width="90" v-if="false" />
            <el-table-column prop="roleName" label="所属角色" width="110" />
            <el-table-column prop="email" label="联系邮箱" width="190" />
            <el-table-column prop="address" label="联系地址" width="200" />
            <el-table-column prop="status" label="状态" width="80" sortable>
                <template #default="{ row }">
                    <el-tag v-if="row.status == '0'" type="danger">停用</el-tag>
                    <el-tag v-if="row.status == '1'" type="success">启用</el-tag>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="200">

                <template #="rs">
                    <el-button link type="primary" size="small"
                        @click="editDialog = true; editDataTransfer(rs.row); getOrg(); getEmployeeRole();">编辑</el-button>

                    <!-- 删除确认框 -->
                    <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消"
                        @confirm="deleteEmployee(rs.row.id)" icon-color="#F56C6C" title="确认删除这个员工？">
                        <template #reference>
                            <el-button link type="primary" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>

            </el-table-column>
        </el-table>
    </div>

    <!-- 底部分页器 -->
    <div v-if="total > 0">
        <div class="page-box">
            <div class="pagination-block">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :small="true" :disabled="false" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getEmployee"
                    @current-change="getEmployee" />
            </div>
        </div>
    </div>

    <!-- 弹出层 -->

    <!-- 新增员工的弹出层 -->
    <el-dialog v-model="createDialog" title="新增员工" width="32%">

        <el-form :model="createForm">

            <el-form-item label="员工姓名">
                <el-input v-model="createForm.name" placeholder="请输入员工姓名" />
            </el-form-item>
            <el-form-item label="员工电话">
                <el-input v-model="createForm.phone" placeholder="请输入员工电话" />
            </el-form-item>
            <el-form-item label="登录密码">
                <el-input v-model="createForm.password" placeholder="请输入登录密码" />
            </el-form-item>
            <el-form-item label="所属组织">
                <el-cascader v-model="createForm.orgId" :options="orgData" :props="cascaderProps" placeholder="请选择组织"
                    clearable />
            </el-form-item>
            <el-form-item label="员工角色">
                <el-select v-model="createForm.roleId" placeholder="请选择员工角色">
                    <el-option v-for="role in roleData" :key="role.id" :value="role.id" :label="role.name">
                    </el-option>
                </el-select>
                <!-- <el-cascader v-model="createForm.roleId" :options="roleData" :props="cascaderProps" placeholder="请选择员工角色"
                    clearable /> -->
            </el-form-item>
            <el-form-item label="员工邮箱">
                <el-input v-model="createForm.email" placeholder="请输入员工邮箱" />
            </el-form-item>
            <el-form-item label="联系地址">
                <el-input v-model="createForm.address" type="textarea" placeholder="请输入员工联系地址" />
            </el-form-item>
            <el-form-item label="账号状态">
                <el-select v-model="createForm.status" placeholder="请选择员工账号状态">
                    <el-option value="1" label="启用" />
                    <el-option value="0" label="禁用" />
                </el-select>
            </el-form-item>

        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="createDialog = false">取消</el-button>
                <el-button type="primary" @click="createEmployee">确认</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑员工的弹出层 -->
    <el-dialog v-model="editDialog" title="编辑员工信息" width="32%">

        <el-form :model="editForm">
            <el-form-item label="员工姓名">
                <el-input v-model="editForm.name" placeholder="请输入员工姓名" />
            </el-form-item>
            <el-form-item label="员工电话">
                <el-input v-model="editForm.phone" placeholder="请输入员工电话" />
            </el-form-item>
            <el-form-item label="所属组织">
                <el-cascader v-model="editForm.orgId" :options="orgData" :props="cascaderProps" placeholder="请选择组织"
                    clearable />
            </el-form-item>
            <el-form-item label="员工角色">
                <el-select v-model="editForm.roleId" placeholder="请选择员工角色">
                    <el-option v-for="role in roleData" :key="role.id" :value="role.id" :label="role.name">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="员工邮箱">
                <el-input v-model="editForm.email" placeholder="请输入员工邮箱" />
            </el-form-item>
            <el-form-item label="联系地址">
                <el-input v-model="editForm.address" type="textarea" placeholder="请输入员工联系地址" />
            </el-form-item>
            <el-form-item label="账号状态">
                <el-select v-model="editForm.status" placeholder="请选择员工账号状态">
                    <el-option value="1" label="启用" />
                    <el-option value="0" label="禁用" />
                </el-select>
            </el-form-item>

        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialog = false">取消</el-button>
                <el-button type="primary" @click="editEmployee">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>



<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();

import { orgGetService } from '@/api/property.js'
import { employeeGetService, employeeDeleteService, employeeCreateService, employeeUpdateService, employeeGetRoleService } from '@/api/user.js'


// 初始化参数
// 按姓名模糊搜索、分页
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const cascaderProps = { // 级联选择框参数
    expandTrigger: 'hover',// as const,
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'name',
}

// 员工
let employeeData = ref([{}])
// 员工组织列表、角色列表
let roleData = ref([{ id: 0, name: '' }])
let orgData = ref([])
// 新增、编辑弹出层的显示/隐藏控制
let createDialog = ref(false)
let editDialog = ref(false)
// 用于创建employee的响应式对象
let createForm = reactive({
    name: null,
    phone: null,
    email: null,
    password: null,
    roleId: null,
    orgId: null,
    address: null,
    status: null
})

// 用于编辑employee的响应式对象
let editForm = reactive({
    id: null,
    name: null,
    phone: null,
    email: null,
    roleId: null,
    orgId: null,
    address: null,
    status: ''
})

// 点击编辑时，数据回显
const editDataTransfer = function (row) {
    editForm = row;
    editForm.status = editForm.status.toString();
}

// 获取员工信息
async function getEmployee() {
    try {
        let result = await employeeGetService(search.value, currentPage.value, pageSize.value);
        if (result.code == 200) {
            employeeData.value = result.data.list;
            total.value = result.data.total;
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
    } catch (error) {
        ElMessage.error('系统异常（getEmployee）')
    }
}
getEmployee();

// 获取org列表
async function getOrg() {
    try {
        let result = await orgGetService(null, 0, 0);
        if (result.code == 200) {
            orgData.value = result.data.list;
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
    } catch (error) {
        ElMessage.error('系统异常（getOrg in employee）')
        console.log(error)
    }
}

// 获取员工角色信息
async function getEmployeeRole() {
    try {
        let result = await employeeGetRoleService();
        if (result.code == 200) {
            roleData.value = result.data;
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
    } catch (error) {
        ElMessage.error('系统异常（getEmployeeRole）')
    }
}

// 新增员工
async function createEmployee() {
    try {
        let result = await employeeCreateService(createForm);
        if (result.code == 200) {
            ElMessage.success(result.msg)
            createDialog.value = false
            getEmployee()
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常（createEmployee）')
    }
}

// 编辑员工信息
async function editEmployee() {
    try {
        let result = await employeeUpdateService(editForm);
        if (result.code == 200) {
            ElMessage.success(result.msg)
            editDialog.value = false
            getEmployee()
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
    } catch (error) {
        ElMessage.error('系统异常（editEmployee）')
    }
}

// 删除员工
async function deleteEmployee(id) {
    try {
        let result = await employeeDeleteService(id);
        if (result.code == 200) {
            ElMessage.success(result.msg)
            getEmployee()
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
    } catch (error) {
        ElMessage.error('系统异常（deleteEmployee）')
    }
}

</script>

<style>
.header {
    margin-bottom: 7px;
}
</style>